package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.Album;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
/*写入表的信息*/
public class QuanZiApiImpl implements QuanZiApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String ,String> redisTemplate;
    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;


    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";


    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        //分析：查询好友的动态，实际上查询时间线表
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        Pageable pageable = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("date")));

        Query query = new Query().with(pageable);
        List<TimeLine> timeLineList = this.mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        if(CollUtil.isEmpty(timeLineList)){
            //没有查询到数据
            return pageInfo;
        }

        //获取时间线列表中的发布id的列表
        List<Object> ids = CollUtil.getFieldValues(timeLineList, "publishId");

        //根据动态id查询动态列表
        Query queryPublish = Query.query(Criteria.where("id").in(ids))
                .with(Sort.by(Sort.Order.desc("created")));

        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);

//        查询推荐的结果数据
        String key="QUANZI_PUBLISH_RECOMMEND_" + userId;
        String data=this.redisTemplate.opsForValue().get(key);
        if (StrUtil.isEmpty(data)){
            return pageInfo;
        }
        List<String> pid = StrUtil.split(data, ',');

//        计算分页
//        [0,10]
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex=startEnd[0];//开始
        int endIndex=Math.min(startEnd[1],pid.size());//结束

        ArrayList<Long> pidLongList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidLongList.add(Long.valueOf(pid.get(i)));
        }
        if (CollUtil.isEmpty(pidLongList)) {
            //没有查询到数据
            return pageInfo;
        }
//        根据pid查询publish（动态）
        Query query=Query.query(Criteria.where("pid").in(pidLongList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);
        if(CollUtil.isEmpty(publishList)){
//            没有查询到数据
            return pageInfo;
        }

        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    /*发布动态*/
    @Override
    public boolean savePublish(Publish publish) {
//        对publish对象进行校验
        if (!ObjectUtil.isAllNotEmpty(publish.getUserId(), publish.getText())) {
//           发布失败，动态为空或者没有发布者id
            return false;
        }
        try {
//        设置主键id(为了设置发布id)
            publish.setId(ObjectId.get());

//        设置自增长pid（发布id）和创建时间
            publish.setPid(this.idService.created(IdType.PUBLISH));
            publish.setCreated(System.currentTimeMillis());

//        写入到publish表中
            this.mongoTemplate.save(publish);
//        将发布时间和发布id写入相册表,主键id是自动增长
            Album album = new Album();
            album.setPublishId(publish.getId());
            album.setCreated(System.currentTimeMillis());
            album.setId(ObjectId.get());
//      将相册表存入相册表中
            this.mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

//        写入好友的时间线表（异步写入）
            this.timeLineService.saveTimeLine(publish.getUserId(), publish.getId());
        } catch (Exception e) {
//            TODO 需要将事务做回滚，Mongodb的是单节点，不支持事务，对于回滚事务暂时就不实现
            log.error("发布动态失败！publish="+publish,e);
        }
        return true;
    }
/*==============*/
    /*根据id去查询*/
    @Override
    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id),Publish.class);
    }
        /*点赞方法*/
    @Override
    public Boolean likeComment(Long userId, String publishId) {
//        不管有没有点赞都会进入这个判断是否点赞的表
//        判断用户是否已经点赞，如果已经点赞直接返回
//        如果没有点赞的话就是保存你这次点赞，并且将总的点赞数目统计
        if(this.queryUserIsLike(userId,publishId)){
            return false;
        }

//        如果没有点赞的话，保存comments要保存redis中
        Boolean result = this.saveComment(userId, publishId, CommentType.LIKE, null);
        if(!result){
//            保存评论失败
            return false;
        }
//        修改redis中的点赞和是否点赞
//        修改点赞数（进这个方法说明是增加点赞数）
        String redisKey=this.getCommentRedisKeyPreFix(publishId);
        String hashKey=CommentType.LIKE.toString();
        this.redisTemplate.opsForHash().increment(redisKey,hashKey,1);

//        用户是否点赞
        String userHashKey=this.getCommentUserLikeRedisKeyPreFix(userId);
//        添加喜欢字段为1
        this.redisTemplate.opsForHash().put(redisKey,userHashKey,"1");
        return true;
    }

        /*取消点赞方法*/
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
//        判断用户是否已经点赞，没有点赞的时候返回不做处理
        if(!this.queryUserIsLike(userId,publishId)){
            return false;
        }
//        如果是点赞了的话来开始删除评论数据（将点赞的信息删除）
        Boolean result=this.removeComment(userId,publishId,CommentType.LIKE);
//        如果结果没有删除成功的话返回false
        if(!result){
            return false;
        }
//        修改redis中的数据，将hashkey中的喜欢字段删除（需要得到对应的rediskey和hashkey）
        String redisKey=this.getCommentRedisKeyPreFix(publishId);
        String hashKey=CommentType.LIKE.toString();
//        调用自动增长方法（将点赞数字减少）
        this.redisTemplate.opsForHash().increment(redisKey,hashKey,-1);
//        删除是否喜欢这个字段(USER_LIKE_{userId})
        String userHashKey=this.getCommentUserLikeRedisKeyPreFix(userId);
        this.redisTemplate.opsForHash().delete(redisKey,userHashKey);

        return true;
    }

    /*查询点赞的数量*/
//    redis中数据为什么会是消失？？？？
    @Override
    public Long queryLikeCount(String publishId) {
//        从redis命中查询，如果命中直接返回就可以
        String redisKey=this.getCommentRedisKeyPreFix(publishId);
        String hashKey=CommentType.LIKE.toString();

//        先从redis中查看是否有数据，如果没有数据的话就从mongodb中找数据并给redis重新赋值
        Object data = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)){
            return Convert.toLong(data);
        }

//        从mongodb中查询数据
        Long count=this.queryCommentCount(publishId,CommentType.LIKE);
//        将数据写入redis中
        this.redisTemplate.opsForHash().put(redisKey,hashKey,String.valueOf(count));
        return count;
    }
//    查询点赞数
    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        return this.mongoTemplate.count(query,Comment.class);
    }
    /*查询是否点赞           */
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
//        从redis中查询数据，如果为空的话去monggodb中查询
        String redisKey=this.getCommentRedisKeyPreFix(publishId);
        String userHashkey=this.getCommentUserLikeRedisKeyPreFix(userId);
        Object data = this.redisTemplate.opsForHash().get(redisKey, userHashkey);
        if (ObjectUtil.isNotEmpty(data)){
            return StrUtil.equals(Convert.toStr(data),"1");
        }
//       查询mongodb，确定是否点赞
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commenType").is(CommentType.LIKE)
        );
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count==0){
            return false;
        }
//        写入到redis中
        this.redisTemplate.opsForHash().put(redisKey,userHashkey,"1");
        return true;
    }

//    =================================================
@Override
public Boolean loveComment(Long userId, String publishId) {
    //查询该用户是否已经喜欢
    if (this.queryUserIsLove(userId, publishId)) {
        return false;
    }

    //喜欢
    boolean result = this.saveComment(userId, publishId, CommentType.LOVE, null);
    if (!result) {
        return false;
    }

    //喜欢成功后，修改Redis中的总的喜欢数
    String redisKey = this.getCommentRedisKeyPreFix(publishId);
    String hashKey = CommentType.LOVE.toString();
    this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

    //标记用户已经喜欢
    hashKey = this.getCommentUserLoveRedisKey(userId);
    this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

    return true;
}



    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        if (!this.queryUserIsLove(userId, publishId)) {
            //如果用户没有喜欢，就直接返回
            return false;
        }

        boolean result = this.removeComment(userId, publishId, CommentType.LOVE);
        if (!result) {
            //删除失败
            return false;
        }

        //删除redis中的记录
        String redisKey = this.getCommentRedisKeyPreFix(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        this.redisTemplate.opsForHash().delete(redisKey, hashKey);
        this.redisTemplate.opsForHash().increment(redisKey, CommentType.LOVE.toString(), -1);

        return true;
    }

    @Override
    public Long queryLoveCount(String publishId) {
        //首先从redis中命中，如果命中的话就返回，没有命中就查询Mongodb
        String redisKey = this.getCommentRedisKeyPreFix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            return Convert.toLong(value);
        }

        //查询count
        Long count = this.queryCommentCount(publishId, CommentType.LOVE);

        //存储到redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));

        return count;
    }

    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKeyPreFix(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            return StrUtil.equals(Convert.toStr(value), "1");
        }

        //查询mongodb
        Query query = Query.query(Criteria.where("publishId")
                .is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LOVE.getType()));
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }

        //标记用户已经喜欢
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        return true;
    }
    //      ===============================
    /*保存comment表在mongodb中*/
    //          保存评论数据
    private Boolean saveComment(Long userId,
                                String publishId,
                                CommentType commentType,
                                String content
                                ){
        try {
            Comment comment = new Comment();

//        评论表的主键id
            comment.setId(ObjectId.get());
//        评论表的用户id（谁来评论的id）
            comment.setUserId(userId);
//        对应动态的id
            comment.setPublishId(new ObjectId(publishId));
//        评论类型
            comment.setCommentType(commentType.getType());
//        评论内容
            comment.setContent(content);
//        评论时间
            comment.setCreated(System.currentTimeMillis());
//        publishUserid（动态发布者的id）
            Publish publish = this.queryPublishById(publishId);
//        TODO 其他评论暂时不做处理
            comment.setPublishUserId(publish.getUserId());
            this.mongoTemplate.save(comment);
            return true;
        } catch (Exception e) {
            log.error("保存出错",e);
        }
//        保存评论表失败
        return false;
    }

    //          删除评论数据
    private Boolean removeComment(Long userId, String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
//        如果删除数据的话就会有数字的变化
        return this.mongoTemplate.remove(query,Comment.class).getDeletedCount()>0;
    }

    //        获取hashkey
    private String getCommentUserLikeRedisKeyPreFix(Long userId) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX+userId;
    }
    //        获取对应rediskey
    private String getCommentRedisKeyPreFix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX+publishId;
    }
    //        获取hashkey
    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }
}
